import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {ReplaySubject} from 'rxjs';


declare var $: any;
import * as echarts from 'echarts';
import * as html2canvas from 'html2canvas';
import Echarts = echarts.Echarts;
import * as _ from 'underscore';
export class CBoardKpiRender {
  private container;
  private options;
  private template = "<div class='small-box {style}'> \
               <div class='inner'> \
                   <h3>{kpiValue}</h3> \
                   <p>{kpiName}</p> \
               </div> \
               <div class='icon'> \
                   <i class='ion ion-stats-bars'></i> \
               </div> \
               <a class='small-box-footer'>\
                   <span ng-click='reload(widget)' style='cursor: pointer'>{refresh} <i class='fa fa-refresh'></i></span>\
                   <span ng-click='config(widget)' ng-if='widgetCfg' style='cursor: pointer'>{edit} <i class='fa fa-wrench'></i></span>\
               </a>\
            </div>";
  constructor(jqContainer, options) {
    console.log('Constructor initialization');
    this.container = jqContainer; // jquery object
    this.options = options;
  }

  public html(persist){
    var self = this;
    var temp = "" + self.template;
    var html = this.render(self.options);
    if (persist) {
      setTimeout(function () {
        self.container.css('background', '#fff');
        html2canvas(self.container, {
          onrendered: function (canvas) {
            persist.data = canvas.toDataURL("image/jpeg");
            persist.type = "jpg";
            persist.widgetType = "kpi";
          }
        });
      }, 1000);
    }
    return html;
  }
  public realTimeTicket(){
    var self = this;
    return function (o) {
      $(self.container).find('h3').html(o.kpiValue);
    }
  }
  public do(){
    var self = this;
    // TODO
    // $(self.container).html(self.rendered());
  }

  private render(context){
    var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
    return this.render2(this.template, context, tokenReg,null,null);
  }
  private render2(template, context, tokenReg, hasDollarPrefix, resultProcessor) {
    return template.replace(tokenReg, function (word, slash1, token, slash2) {
      if (slash1 || slash2) {
        return word.replace('\\', '');
      }
      var variables = token.replace(/\s/g, '').split('.');
      var currentObject = context;
      var i, length, variable;
      for (i = 0, length = variables.length; i < length; ++i) {
        variable = variables[i];
        currentObject = currentObject[variable];
        if (currentObject === undefined || currentObject === null) {
          if (hasDollarPrefix === true) {
            return '${'+token+'}';
          } else {
            return '{'+token+'}';
          }
        }
      }
      if (resultProcessor) {
        return resultProcessor(currentObject);
      } else {
        return currentObject;
      }
    })
  }
}
